package com.interviewbackend.util;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;
import org.springframework.stereotype.Component;
import org.xml.sax.SAXException;
import org.apache.tika.exception.TikaException;

import java.io.ByteArrayInputStream;
import java.io.IOException;

@Component
public class PdfUtil {

    /**
     * 保留原方法名，用于 resumeText = PdfUtil.extractText(fileBytes) 场景
     * 自动检测文件类型并选择合适解析方式
     */
    public static String extractText(byte[] fileBytes) throws IOException {
        String fileType = detectFileType(fileBytes);
        if ("application/pdf".equals(fileType)) {
            return extractPdfText(fileBytes);
        } else if (fileType.contains("word") || fileType.contains("officedocument")) {
            return extractWordTextWithTika(fileBytes);
        } else {
            throw new IllegalArgumentException("不支持的文件类型: " + fileType);
        }
    }

    /**
     * PDF 文件解析
     */
    private static String extractPdfText(byte[] pdfBytes) throws IOException {
        try (PDDocument document = PDDocument.load(pdfBytes)) {
            PDFTextStripper stripper = new PDFTextStripper();
            return stripper.getText(document);
        }
    }

    /**
     * Word 文件解析（兼容 doc 和 docx）
     */
    private static String extractWordTextWithTika(byte[] fileBytes) throws IOException {
        try (ByteArrayInputStream input = new ByteArrayInputStream(fileBytes)) {
            BodyContentHandler handler = new BodyContentHandler(-1);
            AutoDetectParser parser = new AutoDetectParser();
            Metadata metadata = new Metadata();
            parser.parse(input, handler, metadata, new ParseContext());
            return handler.toString();
        } catch (TikaException | SAXException e) {
            throw new IOException("文档解析失败: " + e.getMessage(), e);
        }
    }

    /**
     * 使用 Tika 检测文件 MIME 类型
     */
    private static String detectFileType(byte[] fileBytes) throws IOException {
        org.apache.tika.Tika tika = new org.apache.tika.Tika();
        return tika.detect(fileBytes);
    }
}
